package com.yx.pc.api.quartz;

import com.yx.modules.api.service.SysAuthBookService;
import com.yx.system.entity.SysAuthBook;
import com.yx.system.entity.SysAuthBookInfo;
import com.yx.system.service.SysAuthBookInfoService;
import com.yx.utils.HttpUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 定时器
 *
 * @author luo
 * @date 2018/4/18
 */
@Component
@Configurable
@EnableScheduling
public class QuartzTask {

    @Autowired
    private SysAuthBookService sysAuthBookService;

    @Autowired
    private SysAuthBookInfoService sysAuthBookInfoService;

    /*
    * 订单未付款到时取消监听
    */
    @Scheduled(cron = "0 0 0/1 * * ?")//十秒执行一次
    public void paymentOrder(){
        String client_id = "49";
        String client_secret = "MTUzMTE5MDA5MjM5MQ";
        String sign = HttpUtil.encryption("49MTUzMTE5MDA5MjM5MQ");
        String temp = HttpUtil.sendGet("http://www.quyuewang.cn/api.php/BookList/index?client_id=49&sign="+sign);
        //通过第三方接口获取图书列表
        List<SysAuthBook> sysAuthBooks = HttpUtil.jsonToList(temp,SysAuthBook.class);
        //初始化一个真真需要存储的图书集合
        List<SysAuthBook> authBooks = new ArrayList<>(sysAuthBooks);
        if (sysAuthBooks.size()!=0){
            //获取数据库里面图书列表
            List<SysAuthBook> sysAuthBookList = sysAuthBookService.findAll();

            //数据库数据不为空就进行筛选
            if (sysAuthBookList!=null){
                //循环判断数据库存在就把这存在的数据移除集合
                for (int i = 0;i<sysAuthBooks.size();i++){
                    for (int j = 0;j<sysAuthBookList.size();j++){
                        if (sysAuthBookList.get(j).getId().equals(sysAuthBooks.get(i).getId())){
                            authBooks.remove(sysAuthBooks.get(i));
                            break;
                        }

                    }
                }
            }
            //判断进行保存
            if (authBooks.size()!=0){
                for (SysAuthBook sysAuthBook:authBooks){
                    sysAuthBookService.save(sysAuthBook);
                    String id = sysAuthBook.getId();
                    String sign2 = HttpUtil.encryption("49MTUzMTE5MDA5MjM5MQ"+id);
                    String temp2 = HttpUtil.sendGet("http://www.quyuewang.cn/api.php/BookInfo/index/"+id+"?client_id=49&sign="+sign2);
                    SysAuthBookInfo sysAuthBookInfo = HttpUtil.tobean(temp2,SysAuthBookInfo.class);
                    sysAuthBookInfo.setStatus(0);
                    sysAuthBookInfo.setCreateDate(new Date());
                    sysAuthBookInfo.setUuid("0");
                    sysAuthBookInfoService.save(sysAuthBookInfo);
                }
            }

        }
    }
}
